package com.sun.config;

import com.sun.pojo.WsJobEntity;
import com.sun.repository.WsJobRepository;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import java.util.List;
import java.util.UUID;

import static com.sun.constants.Constant.WS_JOB_DATA;

@Configuration
public class QuartzConfig {

    @Autowired
    private WsJobRepository wsJobRepository;

    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;

    @Bean
    public void initTask() throws ClassNotFoundException, SchedulerException {
        List<WsJobEntity> wsJobs = wsJobRepository.findAll();

        Scheduler scheduler = schedulerFactoryBean.getScheduler();

        for (WsJobEntity wsJob : wsJobs) {
            if(wsJob.getEnabled()) {
                JobDataMap jobData = new JobDataMap();
                jobData.put(WS_JOB_DATA, wsJob);

                String uuid = UUID.randomUUID().toString();
                Class<?> jobClass = Class.forName(wsJob.getDecodeClass());
                JobDetail jobDetail = JobBuilder.newJob((Class<? extends Job>) jobClass)
                        .withIdentity(uuid)
                        .setJobData(jobData)
                        .build();
                CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                        .withIdentity(uuid)
                        .withSchedule(CronScheduleBuilder.cronSchedule(wsJob.getCronExpression()))
                        .build();
                scheduler.scheduleJob(jobDetail, cronTrigger);
            }
        }
        scheduler.start();
    }

}
